package com.pc.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pc.entity.Address;
import com.pc.mapper.AddressMapper;
import com.pc.utils.Result;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressService {
    @Resource
    private AddressMapper addressMapper;

    //根据用户名得到该用户的地址
    public Result getUserAddress(String username){
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        List<Address> addressList = addressMapper.selectList(wrapper);
        return  Result.success("成功",addressList);
    }
    //新增地址 得到用户名先判断该用户是否有默认地址如果没有可以插入如果
    //不能再插入一个默认地址
    public boolean addUserAddress(Address address){
        String username = address.getUsername();
        Integer isdefault = address.getIsdefault();
        if(isdefault>0){
            QueryWrapper<Address> wrapper = new QueryWrapper<>();
            wrapper.eq("username",username).eq("isdefault",1);
            try { //解决不了问题，就不去看它
                Address address1 = addressMapper.selectOne(wrapper);
                System.out.println("打印查询到的"+address1);
                if(address1!=null)
                    return false;
            }catch (Exception e){
                return false;
            }
            int insert = addressMapper.insert(address);
            return insert!=0;
        }

        int insert = addressMapper.insert(address);
        return insert!=0;
    }
    //删除地址
    public boolean delUserAddress(String username,String name,String phone,String ssq,String address){
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username)
                .eq("name",name)
                .eq("phone",phone)
                .eq("area",ssq)
                .eq("address",address);

//        System.out.println(username+" "+name+"  "+phone+" "+ssq+" "+address);
        Address address1 = addressMapper.selectOne(wrapper);
        int delete = addressMapper.delete(wrapper);
//        System.out.println("打印查询到的"+address1);
        return delete!=0;
    }

    //更改地址的默认状态
    public boolean modifyAddressDefault(String username,String name,String phone,String ssq,String address){
        //把这个用户的所有地址全部设置不默认
        QueryWrapper<Address> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username",username);
        Address address2 = new Address();
        address2.setIsdefault(0);
        addressMapper.update(address2,wrapper1);

        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username)
                .eq("name",name)
                .eq("phone",phone)
                .eq("area",ssq)
                .eq("address",address);

        Address address1 = addressMapper.selectOne(wrapper);
        address1.setIsdefault(1);
        int update = addressMapper.update(address1, wrapper);
        return update!=0;
    }
}
